<template>
  <div class="errata">
    <div class="errata-header-wrapper">
      <flex class="tabs">
        <div
          :class="{ select: activeIndex === 0 }"
          class="tab-item"
          @click="handleSelect(0)"
        >
          <el-badge style="font-weight: bold"> 智能勘误 </el-badge>
        </div>
        <div
          :class="{ select: activeIndex === 1 }"
          class="tab-item"
          @click="handleSelect(1)"
        >
          <el-badge
            style="font-weight: bold"
            :value="promptListCount"
            :max="99"
            :hidden="!promptListCount"
          >
            辅助提示
          </el-badge>
        </div>
      </flex>
    </div>
    <flex align="center" class="select-wrapper">
      <el-select
        v-model="selectType"
        multiple
        collapse-tags
        :placeholder="'全部提示(' + errorListNotTypeFilter.length + ')'"
        style="flex: 1; margin-right: 15px"
      >
        <el-option
          v-for="item in setclassify"
          :key="item.kind"
          :value="item.kind"
          :label="item.text + '(' + setLengthTip(item.kind) + ')'"
        >
          <div class="_corrention_lists_re-option">
            <i
              :style="{ backgroundColor: item.color }"
              class="_corrention_lists_re-option-dot"
            />
            <span>{{ item.text }}({{ setLengthTip(item.kind) }})</span>
          </div>
        </el-option>
      </el-select>
      <el-button
        :loading="checkLoading"
        type="primary"
        @click="handleCheck"
        style="flex: none; width: 80px"
      >
        检查
      </el-button>
    </flex>
    <!-- 全能 -->
    <div v-if="activeIndex === 0" class="panel-header-radios-error">
      <el-radio-group v-model="selectErrorLevel" size="small">
        <el-radio-button
          v-for="level in levelList"
          :key="level.value"
          :label="level.value"
          :class="level.class"
        >
          <div class="radios-error-text">
            {{ level.label }}
          </div>
          <div class="radios-error-text">
            {{ errorLevelCount(level) }}
          </div>
        </el-radio-button>
      </el-radio-group>
    </div>
    <div class="error-list-title">
      <span class="title-text">检查结果</span>
      <div v-if="activeIndex === 0" class="filter">
        <el-radio-group v-model="selCheckedTab">
          <el-radio-button :label="0" border>未处理</el-radio-button>
          <el-radio-button :label="1" border>已忽略</el-radio-button>
          <el-radio-button :label="2" border>已替换/删除</el-radio-button>
        </el-radio-group>
      </div>
    </div>
    <div class="error-list-wrapper">
      <el-scrollbar class="main-scroll">
        <div
          v-for="(item, index) in errorListByFilter"
          :key="index"
          class="block"
          @click="onRowClick(item)"
        >
          <i class="decorate" :style="{ backgroundColor: item.color }" />
          <div class="analysis-data">
            <flex
              v-if="activeIndex === 0"
              justify="between"
              align="start"
              class="suggest"
            >
              <div :title="item.word" class="word">{{ item.word }}</div>
              <div v-if="item.opt === type1" class="connect">
                建议{{ item.pre_insert ? '在之前' : '在之后' }}添加
              </div>
              <div v-else-if="item.opt === type2" class="connect">建议删除</div>
              <div v-else-if="item.opt === type3" class="connect">
                {{
                  item.correct ||
                  (item.checkType && !item.checkType.includes('office'))
                    ? '不建议使用'
                    : ''
                }}
              </div>
              <div v-else class="connect">建议替换为</div>
              <div
                v-if="item.opt !== type3 && item.opt !== type2"
                :title="item.correct"
                class="word"
                style="text-align: center"
              >
                {{ item.correct }}
              </div>
            </flex>
            <flex v-else class="suggest">
              <div :title="item.word" class="word">{{ item.word }}</div>
              <div class="connect">建议替换为</div>
              <div
                :title="item.correct"
                class="word"
                style="text-align: center"
              >
                {{ item.correct }}
              </div>
            </flex>
            <div class="options">
              <div>错误原因：{{ item.type }}</div>
              <div class="option-wrap">
                <el-button
                  v-if="
                    selCheckedTab === 0 &&
                    activeIndex === 0 &&
                    item.opt !== type3 &&
                    !(item.optionList && item.optionList.length)
                  "
                  type="primary"
                  :loading="operateLoading === item.uid"
                  :disabled="
                    operateLoading !== '' && operateLoading !== item.uid
                  "
                  @click.stop="handleOperateText(item)"
                  >{{
                    item.opt === type1
                      ? '添加'
                      : item.opt === type2
                      ? '删除'
                      : '替换'
                  }}
                </el-button>
                <el-dropdown
                  v-if="
                    selCheckedTab === 0 &&
                    activeIndex === 0 &&
                    item.opt !== type3 &&
                    item.optionList &&
                    item.optionList.length
                  "
                  size="small"
                  trigger="click"
                >
                  <el-button
                    :loading="operateLoading === item.uid"
                    :disabled="
                      operateLoading !== '' && operateLoading !== item.uid
                    "
                    style="margin-right: 10px"
                    class="option"
                    size="small"
                  >
                    替换
                  </el-button>
                  <el-dropdown-menu slot="dropdown" class="default-dropdown">
                    <el-dropdown-item
                      v-for="(option, optionIndex) in item.optionList"
                      :key="option + optionIndex"
                      @click.native="handleOperateText(item, option)"
                    >
                      {{ option }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
                <el-button
                  v-if="activeIndex === 0 && selCheckedTab === 0"
                  class="option"
                  :disabled="
                    operateLoading !== '' && operateLoading !== item.uid
                  "
                  @click.stop="handleIgnore(item)"
                >
                  <span
                    v-if="
                      item.checkType && item.checkType === 'office_deletion'
                    "
                  >
                    忽略缺失
                  </span>
                  <span v-else> 忽略 </span>
                </el-button>
                <el-button
                  v-if="activeIndex === 1"
                  class="option"
                  :disabled="
                    operateLoading !== '' && operateLoading !== item.uid
                  "
                  @click.stop="handleIgnore(item)"
                >
                  <span> 忽略 </span>
                </el-button>
              </div>

              <div v-show="activeIndex === 0 && selCheckedTab === 1">
                <el-button
                  class="option"
                  :disabled="
                    operateLoading !== '' && operateLoading !== item.uid
                  "
                  @click.stop="onUnIgnore(item)"
                >
                  <span
                    v-if="
                      item.checkType && item.checkType === 'office_deletion'
                    "
                  >
                    取消缺失
                  </span>
                  <span v-else> 取消忽略 </span>
                </el-button>
              </div>
              <div v-show="activeIndex === 0 && selCheckedTab === 2">
                <el-button
                  class="option"
                  :disabled="
                    operateLoading !== '' && operateLoading !== item.uid
                  "
                  @click.stop="onUnProcessClick(item)"
                >
                  {{ item.opt === '插入' ? '撤消添加' : '撤消' + item.opt }}
                </el-button>
              </div>
            </div>
          </div>
          <el-collapse
            v-if="item.explain || item.source || item.origin"
            v-model="collapseActives"
          >
            <el-collapse-item
              :title="item.origin ? item.origin : '点击查看错误详情'"
              :name="item.word + index"
            >
              <div class="analysis-note-wrapper">
                <div v-if="item.explain" class="analysis-explain">
                  {{ item.explain }}
                </div>
                <div v-if="item.source" class="analysis-knowledge">
                  <span class="knowledge-title">来源链接</span>
                  <div class="knowledge-url" @click="toUrl(item)">
                    {{ item.source }}
                  </div>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
      </el-scrollbar>
    </div>
  </div>
</template>

<script>
// import md5 from 'js-md5';
// import crypto from 'crypto';
import * as api from '@/api/index.js'
//------------cx----
// import Rabas from '@/components/ribbon.js';
// import Util from '@/components/js/util.js';
import Axios from 'axios'

// --------------

const MAXSTRING = 1000

export default {
  data() {
    return {
      seed: 9999999999,
      spinning: false,
      docname: '', // 当前文章名称
      selectType: [], // 选择的错误类型
      DocCheckList: {}, //多文档的检查结果
      DocStyleInfo: {}, //多文档，用于保存各文档的原始样式信息
      BTextList: {}, //记录批次文本用于操作接口
      activeIndex: 0, // 0-智能勘误 1-辅助提示
      checkLoading: false, // 加载
      selCheckedTab: 0, // 未处理 0， 已忽略 1，已替换/删除 2
      selectErrorLevel: -1,
      levelList: [
        {
          label: '全部错误',
          class: 'error-all',
          value: -1,
        },
        {
          label: '严重错误',
          class: 'error-serious',
          value: 1,
        },
        {
          label: '一般错误',
          class: 'error-general',
          value: 2,
        },
        {
          label: '疑似错误',
          class: 'error-suspected',
          value: 3,
        },
        {
          label: '自定义错误',
          class: 'error-customize',
          value: 0,
        },
      ],
      type1: '插入', // 少字
      type2: '删除', // 多字
      type3: '无',
      classify: [
        {
          text: '字词语法类',
          prop: 'grammar_word',
          number: 0,
          kind: 5,
          WdColor: 8388736, // wdColorViolet	8388736	紫色。
          color: '#AA67FF',
        },
        {
          text: '领导人政治类',
          prop: 'leader',
          number: 0,
          kind: 3,
          WdColor: 255, // wdColorRed	255	红色。
          color: '#FF6E8B',
        },
        {
          text: '敏感词类',
          prop: 'sensitive',
          number: 0,
          kind: 2,
          WdColor: 65535, // wdColorYellow	65535	黄色。
          color: '#F4E53D',
        },
        {
          text: '禁用词类',
          prop: 'forbidden',
          number: 0,
          kind: 4,
          WdColor: 16711680, // wdColorBlue	16711680	蓝色。
          color: '#558BFF',
        },
        {
          text: '标点类',
          prop: 'punctuation',
          number: 0,
          kind: 1,
          WdColor: 32768, // wdColorGreen	32768	绿色。
          color: '#85C765',
        },
        {
          text: '规范术语类',
          prop: 'term',
          number: 0,
          kind: 6,
          WdColor: 8421376, // wdColorTeal	8421376	青色。
          color: '#54D1DF',
        },
        {
          text: '敏感官员类',
          prop: 'officer',
          number: 0,
          kind: 7,
          WdColor: 26367, // wdColorOrange	26367	橙色。
          color: '#FFA969',
        },
      ],
      selectArr: [],
      collapseActives: [],
      docText: '',
      total: {},
      operateLoading: '',
      untreatedList: {}, // 未处理列表
      ingoreList: {}, // 忽略列表
      operateList: {}, // 已处理列表
      officeTypeList: [], // word文档类型 元素
      mustElements: [
        '份号',
        '密级',
        '紧急程度',
        '发文机关标志',
        '发文字号',
        '标题',
        '主送机关',
        '正文',
        '附注',
        '附件',
        '发文机关署名',
        '签发人',
        '成文日期',
        '抄送机关',
        '印发机关',
        '印发日期',
      ],

      remberTeShuStr: [], //标记特殊字符的集合
    }
  },
  computed: {
    //过滤错误类型长度(判断错误类型的数组)
    setclassify() {
      if (this.errorListNotTypeFilter && this.errorListNotTypeFilter.length) {
        return this.classify.filter(
          (v) =>
            this.errorListNotTypeFilter.filter((f) => v.kind === f.kind).length
        )
      }
      return []
    },
    filterSortError() {
      let list = []
      // debugger
      // 原来逻辑  selCheckedTab 代表选择的错误类型 0-未处理 1-已忽略 2-已替换/删除
      if (this.activeIndex === 0) {
        if (this.selCheckedTab === 0) {
          list = this.untreatedList[this.docname]
          return list || []
        } else if (this.selCheckedTab === 1) {
          list = this.ingoreList[this.docname]
          return list || []
        } else {
          list = this.operateList[this.docname]
          return list || []
        }
      } else {
        list = this.untreatedList[this.docname]
        return list || []
      }
    },
    // 用于分类显示
    errorListNotTypeFilter() {
      if (this.activeIndex === 0) {
        let list =
          this.filterSortError &&
          this.filterSortError.filter(
            (v) =>
              (v.label_type === 0 || !v.label_type) &&
              (v.label === this.selectErrorLevel ||
                this.selectErrorLevel === -1)
          )
        return list || []
      } else {
        let list =
          this.filterSortError &&
          this.filterSortError.filter((v) => v.label_type === 1)
        return list || []
      }
    },

    //辅助提示的错误badge数量
    promptListCount() {
      return (
        (this.untreatedList[this.docname] &&
          this.untreatedList[this.docname].filter((v) => v.label_type === 1)
            .length) ||
        0
      )
    },

    // 根据选择的错误等级和错误类型过滤错误列表
    errorListByFilter() {
      // console.log('selCheckedTab',this.selCheckedTab);
      let list = []
      // 0-智能勘误 1-辅助提示
      if (this.activeIndex === 0) {
        list =
          this.filterSortError &&
          this.filterSortError.filter(
            (v) =>
              (!this.selectType ||
                !this.selectType.length ||
                this.selectType.includes(v.kind)) &&
              (v.label_type === 0 || !v.label_type) &&
              (v.label === this.selectErrorLevel ||
                this.selectErrorLevel === -1)
          )
        return list ? list : []
      } else {
        list =
          this.filterSortError &&
          this.filterSortError.filter(
            (v) =>
              (!this.selectType ||
                !this.selectType.length ||
                this.selectType.includes(v.key)) &&
              v.label_type === 1
          )
        return list ? list : []
      }
    },
    // 统计不通错误等级的错误数量
    errorLevelCount() {
      return (level) => {
        let errorList =
          this.filterSortError &&
          this.filterSortError.filter(
            (v) =>
              (!this.selectType ||
                !this.selectType.length ||
                this.selectType.includes(v.kind)) &&
              (v.label_type === 0 || !v.label_type) &&
              (v.label === level.value || level.value === -1)
          )
        return errorList ? errorList.length : 0
      }
    },
  },
  created() {
    this.seed = Date.parse(new Date()) / 1000
    try {
    if(window.c_methods){
      let docInfo=JSON.parse(window.c_methods.getDocInfo()).data
      this.docname = docInfo.name||'关于开展全市高速安全大整治的通知'
    }else{
      this.docname = '关于开展全市高速安全大整治的通知'
    }
   } catch (error) {
    console.log(error);
   }

    this.getOfficeAllTypeList()
  },
  beforeDestroy() {
    // wps.ApiEvent.RemoveApiEventListener('AfterTaskPaneHidden');
    // wps.ApiEvent.RemoveApiEventListener('DocumentBeforeSave');
  },
  mounted() {
    // wps.ApiEvent.AddApiEventListener('AfterTaskPaneHidden', () => {
    //   this.handlePaneHidden();
    // });
    // this.timer = setInterval(() => {
    //   // 正在检查文档的时候，不要监听文档切换，防止数据串档
    //   if (!this.spinning) {
    //     this.docname = wps.WpsApplication().ActiveDocument.Name; //监听活动文档的变动
    //     let tempNameList = [];
    //     for (var i = 1; i <= wps.WpsApplication().Documents.Count; i++) {
    //       tempNameList.push(wps.WpsApplication().Documents.Item(i).Name);
    //     }
    //     if (this.DocCheckList) {
    //       Object.keys(this.DocCheckList).map((key) => {
    //         if (tempNameList.indexOf(key) < 0) {
    //           this.DocCheckList[key] = null;
    //           // delete this.DocCheckList[key]
    //         }
    //       });
    //     }
    //   }
    // }, 500);
    // this.checkUpdate();
  },
  methods: {
    setLengthTip(kind) {
      if (this.errorListNotTypeFilter && this.errorListNotTypeFilter.length)
        return this.errorListNotTypeFilter.filter((v) => v.kind === kind).length
      return 0
    },
    // 获取所有公文模板的要素列表
    getOfficeAllTypeList() {
      // window.alert('获取所有公文模板的要素列表')
      api.getOfficeTypeList().then((res) => {
        const data = res.data
        for (let key in data) {
          this.officeTypeList.push({
            label: key,
            elements: data[key].map((v) => {
              return {
                label: v.text,
                origin: v.origin,
                reason: v.reason,
              }
            }),
          })
        }
      })
    },
    handleSelect(index) {
      this.activeIndex = index // 切换tab 0 智能勘误，1 辅助提示
      this.selectType = []
    },
    // 获取文章id
    getDocId(adoc) {
      // let s = adoc.Path + wps.WpsApplication().Application.PathSeparator + this.docname + '-' + this.seed;
      // return md5(s);
      return JSON.parse(window.c_methods.getDocId()).data
    },
    // 获取错误
    getErr(item) {
      return {
        uid: item.uid,
        correct: item.correct,
        offset: item.offset,
        start: item.start,
        end: item.end,
        type: item.type,
        word: item.word,
      }
    },
    // 将API返回的多种类型的结果，整合到一个数组中去，并排序
    getErrataList(data) {
      let ErrataList = []
      let punctuation = data?.punctuation || [] //（1）punctuation：List<JSON> 标点检测结果
      punctuation = punctuation.map((item) => {
        return { ...item, kind: 1 }
      })
      let sensitive = data?.sensitive || [] //（2）sensitive：List<JSON>  敏感词检测结果
      sensitive = sensitive.map((item) => {
        return { ...item, kind: 2 }
      })
      let leader = data?.leader || [] //（3）leader：List<JSON> 政要人名类检测结果
      leader = leader.map((item) => {
        return { ...item, kind: 3 }
      })
      let forbidden = data?.forbidden || [] //（4）forbidden：List<JSON> 禁用词类检测结果
      forbidden = forbidden.map((item) => {
        return { ...item, kind: 4 }
      })
      let grammar_word = data?.grammar_word || [] //（5）grammar_word：List<JSON> 字词语法类检测结果
      grammar_word = grammar_word.map((item) => {
        return { ...item, kind: 5 }
      })
      let term = data?.term || [] //（6）term：List<JSON> 规范术语类检测结果
      term = term.map((item) => {
        return { ...item, kind: 6 }
      })
      let officer = data?.officer || [] //（7）officer：List<JSON> 敏感官员类检测结果
      officer = officer.map((item) => {
        return { ...item, kind: 7 }
      })
      // ErrataList = ErrataList.concat(punctuation).concat(sensitive).concat(leader).concat(forbidden).concat(grammar_word).concat(term).concat(officer);
      ErrataList = ErrataList.concat(
        punctuation,
        sensitive,
        leader,
        forbidden,
        grammar_word,
        term,
        officer
      ).map((M) => {
        let op = ''
        if (M.opt === '无') {
          op = ''
        } else if (M.opt === '删除') {
          op = '建议删除'
        } else if (M.opt === '插入') {
          if (M.pre_insert) {
            op = '建议在之前添加'
          } else {
            op = '建议在之后添加'
          }
        } else {
          op = '建议替换为'
        }
        return {
          ...M,
          _start: M.start,
          _end: M.end,
          words_wrong: M.word, //原词
          error_reason: M.type, //错误原因
          words_new: M.opt === '删除' || M.opt === '无' ? '' : M.correct, //纠正词
          error_tips:
            (Object.prototype.toString.call(M.num) === '[object String]'
              ? M.num + '  '
              : '') +
            (M.opt === '删除' || M.opt === '替换' || M.opt === '插入'
              ? ''
              : M.correct), //提示

          // op: M.opt==='无'?'':(M.opt==='删除'?'建议删除':'建议替换为'),
          op,
          isSub: 0,
          polluting: 0, // 是否被处理污染过
        }
      })
      return ErrataList.sort(function (a, b) {
        return a.start - b.start
      })
    },

    // 移除登录消息，及隐藏所有面板
    RemoveLoinInfoAndPane(type) {
      wps.PluginStorage.removeItem('User')
      wps.PluginStorage.removeItem('Company')
      wps.PluginStorage.removeItem('LoginInfo') // 移除登录消息
      wps.PluginStorage.removeItem('taskShow')
      wps.PluginStorage.removeItem('inLogin') // 移除登录状态

      Object.keys(Rabas.PANE_Enum).forEach(function (key) {
        let tsId = wps.PluginStorage.getItem(key)
        if (tsId) {
          wps.GetTaskPane(tsId).Visible = false
        }
      })
      //cx 修改
      if (type === 'relogin') {
        Rabas.ShowTaskpane('taskpane_login', Util.GetUrlPath() + 'login', 500) // 显示登录页面
      }
    },

    getTextWithHiddenChars(doc, index) {
      try {
        // 1. 保存原始视图设置
        const originalShowAll = doc.ActiveWindow.View.ShowAll
        const originalShowHidden = doc.ActiveWindow.View.ShowHiddenText
        const originalShowFieldCodes = doc.ActiveWindow.View.ShowFieldCodes

        // 2. 显示所有隐藏内容
        doc.ActiveWindow.View.ShowAll = true
        doc.ActiveWindow.View.ShowHiddenText = true
        doc.ActiveWindow.View.ShowFieldCodes = true

        // 3. 获取包含隐藏字符的文本
        const para = doc.Paragraphs.Item(index)
        const fullText = para.Range.Text

        // 4. 恢复原始视图设置
        doc.ActiveWindow.View.ShowAll = originalShowAll
        doc.ActiveWindow.View.ShowHiddenText = originalShowHidden
        doc.ActiveWindow.View.ShowFieldCodes = originalShowFieldCodes

        return fullText
      } catch (error) {
        console.error('获取文本失败:', error)
        return null
      }
    },

    findTermPositions(paragraph, searchTerm) {
      const positions = []
      let index = paragraph.indexOf(searchTerm)
      while (index !== -1) {
        positions.push(index)
        index = paragraph.indexOf(searchTerm, index + 1)
      }
      return positions
    },

    getDocText() {
      // const searchTerm = '\r\u0007'
      const searchTerm = '\r\u0007'
      this.remberTeShuStr = []
      let str = ''
      let oldStr = ''
      try {
        if (!window.c_methods) return ''
        //  var str=window.c_methods.getParagraphSize()
        let result = window.c_methods.getParagraphs()
        if (typeof result === 'string') {
          let obj = JSON.parse(result)
          let data = obj.data
          if (data && data.length > 0) {
            data.forEach((ig, igx) => {
              oldStr += ig+'\n'
              // window.alert(JSON.stringify(this.findTermPositions(ig, searchTerm)))
              // window.alert(JSON.stringify(ig))
              // window.alert(this.findTermPositions(ig, searchTerm))
              let arr = this.findTermPositions(ig, searchTerm) || []
              // if (arr && arr.length > 0) {
              //   // str += ig.replace(/\r\u0007/g, '')
              //   // str += ig.replace(/\u0007/g, '')
              //   str += ig.replace(/\u0007\r/g, '')
              //   // str += ig
              // } else {
              //   str += ig
              // }
              str += ig.replace(new RegExp('\r\u0007', 'g'), '')+'\n'
            })
          }

          // window.alert(
          //   JSON.stringify(this.findTermPositions(oldStr, searchTerm))
          // )
          this.remberTeShuStr = this.findTermPositions(oldStr, searchTerm)
          // window.alert(JSON.stringify(oldStr))
          // window.alert(JSON.stringify(str))
          return str
        } else {
          // alert('数据不是字符串')
          return ''
        }
      } catch (error) {
        return ''
      }
      // return "000001\r\n加急\r\nXX省公路局文件\r\nX路通〔20XX〕111号\r\u0007\n\r\u0007\n\r\n\r\n关于开展全市高速安全大整治的通知\r\n\r\n各省、自治区、直辖市、新将生产建设兵团交通运输厅（局、委）：\r\n为贯彻：\r\n\r\n"
      // return '4555习金平\n\n贷快机构\n'
    },

    // 检查得到结果进行处理
    getResultGoto(result) {
      // window.alert('444' + JSON.stringify(result))
      // let ErrataList = []
      let _ErrataList = [] //记录处理的检查列表结果
      // 按段落循环 开始
      let Paragraphs = []
      if (window.c_methods) {
        // const PC = JSON.parse(window.c_methods.getParagraphSize()).data // 文档自然段落总数
        // window.alert(PC)
        let presult = JSON.parse(window.c_methods.getParagraphs()).data
        // window.alert(presult.length)
        Paragraphs = presult
      }
      // window.alert('Paragraphs' + JSON.stringify(Paragraphs))
      let tempList = []
      tempList = this.getErrataList(result) // 将API返回的多种类型的结果，整合到一个数组中去，并排序
      // window.alert('tempList' + JSON.stringify(tempList))
      // window.alert('Paragraphs' + JSON.stringify(Paragraphs))

      _ErrataList = tempList.map((M) => {
        // console.log(`start ${M._start}-${offset}=${M._start - offset}`);
        M.start = M._start
        M.end = M._start + M.offset
        M.color = this.classify.find((v) => v.kind === M.kind).color
        M.has = true // 是否已经存在于 _ErrataList, 有时会存在因为下标导致的重复问题
        return {
          ...M,
          Paragraph_id: 0,
        }
      })

      // window.alert('88' + JSON.stringify(_ErrataList))
      //记录最新的结果

      //还原上次查询的（忽略等操作）处理状态
      _ErrataList = _ErrataList.map((item) => {
        const status = (this.DocCheckList[this.docname] || []).find(
          (o) =>
            o.status === 2 &&
            o.Paragraph_id === item.Paragraph_id &&
            o.word === item.word &&
            o.start === item.start &&
            o.end === item.end
        )
          ? 2
          : 0
        return {
          ...item,
          status,
        }
      })

      // 排序 （按段落号、坐标，大问题排先）
      _ErrataList.sort(function (a, b) {
        if (a.Paragraph_id === b.Paragraph_id && a.start === b.start) {
          return b.end - a.end // start相同时，end按倒序优先
        } else {
          return a.Paragraph_id - b.Paragraph_id || a.start - b.start // start按升序优先
        }
      })

      // 清空书签 自定义书签清空
      if (window.c_methods) {
        // 获取所有书签
        // window.c_methods.removeBookmarks()
        // window.alert(window.c_methods.getBookmarks())
        let alls=JSON.parse(window.c_methods.getBookmarks()).data
        alls.forEach((ig) => {
          if(ig.name.indexOf('jiaodui_offline_')>-1||ig.name.indexOf('_Bookmark_office_')>-1){
            window.c_methods.removeBookmark(ig.name)
          }
        })
      }

      //创建书签(校对类)
      //特殊字符位置
      _ErrataList.map((item, index) => {
        var arrRember = this.remberTeShuStr.filter((ig) => ig < item._end)
        if (arrRember.length && window.c_methods) {
          window.c_methods.createBookmark(
            'jiaodui_offline_' + index,
            item._start + arrRember.length + 1,
            item._start + arrRember.length + item.offset + 1
          )
        } else {
          window.c_methods.createBookmark(
            'jiaodui_offline_' + index,
            item._start,
            item._start + item.offset
          )
        }
        item.bookMarks = 'jiaodui_offline_' + index
      })
      this.$set(
        this.DocCheckList,
        this.docname,
        this.DocCheckList[this.docname].concat(
          _ErrataList.filter((item) => item.status === 0)
        )
      ) // 获取最新未处理数据
      //添加书签
      // window.alert('99'+JSON.stringify(this.DocCheckList))
      this.setAllList()
      this.spinning = false
      // this.checkLoading = false //是否在处理中，是使检查按钮不可用
      // this.handleOfficeCheck(); //公文勘误
      this.$message({
        type: 'success',
        message: '检查完成',
        duration: 1000,
      })
      this.handleOfficeCheck() //公文勘误
    },
    // 检查
    async handleCheck() {
      this.classify.map((item) => (item.number = 0)) // 初始错误数量为0
      // let adoc = wps.WpsApplication().ActiveDocument;
      // const NameMd5 = crypto.createHash('md5').update(this.docname).digest('hex');
      if(!this.docname&&window.c_methods){
       let docInfo=JSON.parse(window.c_methods.getDocInfo()).data
       this.docname = docInfo.name||'关于开展全市高速安全大整治的通知'
      }else{
         this.docname =this.docname||'关于开展全市高速安全大整治的通知'
      }
      let doc = this.getDocText() // 获取文档文本
      // window.alert('444' + JSON.stringify(doc))

      if (doc == 'undefined' || !doc || !/[^\s]/.test(doc)) {
        this.$message.error('文档内容为空!')
      } else {
        this.DocCheckList[this.docname] = []

        this.$set(this, 'checkLoading', true)
        this.selCheckedTab = 0 // 返回“未处理”tab页

        if (window.c_methods) {
          var _this = this
          try {
            // // linebreak 下标中是否需要计算\n的长度（0=计算，1=不算）
            // // filterIgnore 是否需要过滤用户忽略的结果 （1=过滤，0=不过滤）
            // // combine 是否需要合并下标相同的结果 （0=不合并，1=合并）
            var data = JSON.stringify({
              docId:
                window.c_methods.getDocId() ||
                '3215B8692729E1340718D48D56D71317',
              text: doc,//文字内容
              linebreak: 1,//下标中是否需要计算\n的长度（0=计算，1=不算）
              filterIgnore: 0,
              combine: 1,
              moduler: [],
              isOfficial: true,
              request_info: {
                section_index: 0, //记录调用API次数
                // postTime: 1742151010,
                terminal: 'wps',
                system_info: 'Win10',
              },
              token: window.localStorage.getItem('token'),
            })

            var xhr = new XMLHttpRequest()
            xhr.open(
              'POST',
              'https://jd.dacube.com.cn/correct/api/accessToken',
              true
            )
            xhr.setRequestHeader('Content-Type', 'text/plain;charset=UTF-8')
            xhr.onreadystatechange = function () {
              if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                  var result = JSON.parse(xhr.responseText).data
                  if (result && result.code === 5000) {
                    _this.$message.error('用户验证失败！')
                    window.c_methods.removeToken()
                  } else {
                    // _this.getResultGoto(result);
                    // window.alert('7'+JSON.stringify(result))
                    _this.getResultGoto(result)
                  }
                } else {
                  _this.$message.error('检查失败稍后再试！')
                }
                _this.$set(_this, 'checkLoading', false)
              }
            }

            xhr.send(data)
          } catch (error) {
            _this.$set(this, 'checkLoading', false)
            window.alert(JSON.stringify(error))
            console.log(error)
          }
        }
      }
    },

    setOffieArr(officeErrataList, data) {
      if (!officeErrataList || officeErrataList.length <= 0) return
      // 公文校对添加书签 排序
      officeErrataList.sort(function (a, b) {
        return a.start - b.start
      })

      let newOfficeErrataList = []
      // window.alert('uu'+JSON.stringify(officeErrataList))
      newOfficeErrataList = officeErrataList.map((M) => {
        M.start = M.start
        M.end = M.end
        M.has = true // 是否已经存在于 newOfficeErrataList, 有时会存在因为下标导致的重复问题
        return {
          ...M,
          Paragraph_id: 0,
        }
      })

      // console.log('officeErrataList',officeErrataList);
      // debugger

      // window.alert(JSON.stringify(newOfficeErrataList))

      // console.log('newOfficeErrataList',newOfficeErrataList);

      newOfficeErrataList.map((item, index) => {
        var arrRember = this.remberTeShuStr.filter((ig) => ig < item.end)
        if (arrRember.length && window.c_methods) {
          window.c_methods.createBookmark(
            '_Bookmark_office_' + index,
            item.start + arrRember.length + 1,
            item.end + arrRember.length + 1
          )
        } else {
          window.c_methods.createBookmark(
            '_Bookmark_office_' + index,
            item.start,
            item.end
          )
        }
        item.bookMarks = '_Bookmark_office_' + index
      })

      this.DocCheckList[this.docname] = newOfficeErrataList
        .map((item) => {
          return {
            ...item,
            color: '#FF6E8B',
            checkType: 'office',
            words_wrong: item.word, //原词
            words_new:
              item.opt === '删除' || item.opt === '无' ? '' : item.correct,
            label_type: '',
            label: 1,
            status: 0,
            explain: item.reason,
            word: item.word || item.type,
          }
        })
        .concat(this.DocCheckList[this.docname])
      // 添加书签

      // 如果勘误结果有type，则增加元素缺失错误判断
      let list = []
      if (data.type) {
        let selectTypesElements = this.officeTypeList.find(
          (item) => item.label === data.type
        )
        selectTypesElements.elements.forEach((element) => {
          if (
            !data.elements.find((item) => item.officeKey === element.label) &&
            this.mustElements.includes(element.label) &&
            element.label !== '密级'
          ) {
            list.push({
              start: 0,
              end: 0,
              offset: 0,
              color: '#FF6E8B',
              opt: '无',
              word: `【${element.label}】缺失`,
              // reason: `${element.label}缺失`,
              type: `【${element.label}】缺失`,
              origin: element.origin,
              explain: element.reason,
              checkType: 'office_deletion',
              label_type: '',
              label: 1,
              status: 0,
            })
          }
        })
      }
      this.DocCheckList[this.docname] = list.concat(
        this.DocCheckList[this.docname]
      )

      this.setAllList()
    },
    // 公文勘误
    handleOfficeCheck() {
      var doc = this.getDocText() // 获取文档文本
      var _this = this
      var xhr = new XMLHttpRequest()
      xhr.open('POST', 'https://jd.dacube.com.cn/office/check', true) // 替换为你的 URL
      xhr.setRequestHeader('Content-Type', 'text/plain;charset=UTF-8')
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (xhr.status >= 200 && xhr.status < 300) {
            // window.alert(xhr.responseText)
            let data = JSON.parse(xhr.responseText).data
            let officeErrataList = data.checkResult || []
            _this.setOffieArr(officeErrataList, data)
          }
        }
      }
      xhr.onerror = function () {
        window.alert(
          '请求失败:' + xhr.status + xhr.statusText + xhr.responseText
        )
      }
      xhr.send(JSON.stringify({ text: doc }))
    },
    setAllList() {
      //设置所有列表 0 未处理 1 忽略 2 已处理
      this.$set(
        this.untreatedList,
        this.docname,
        (this.DocCheckList[this.docname] &&
          this.DocCheckList[this.docname].filter((v) => v.status === 0)) ||
          []
      )
      this.$set(
        this.ingoreList,
        this.docname,
        (this.DocCheckList[this.docname] &&
          this.DocCheckList[this.docname].filter((v) => v.status === 1)) ||
          []
      )
      this.$set(
        this.operateList,
        this.docname,
        (this.DocCheckList[this.docname] &&
          this.DocCheckList[this.docname].filter((v) => v.status === 2)) ||
          []
      )
    },
    // 单击检查结果中的行
    onRowClick(item) {
      // window.alert(JSON.stringify(item.bookMarks))
      // window.alert(JSON.stringify(this.remberTeShuStr))
      //缺失类不做处理
      if (item.checkType && item.checkType === 'office_deletion') {
        // window.alert('office_deletion')
        this.$message.error('该类错误不支持处理')
        return
      }
      if (item.bookMarks) {
        // window.alert('uu')
        var bookRang = JSON.parse(
          window.c_methods.getBookmark(item.bookMarks)
        ).data
        // window.alert(JSON.stringify(bookRang))
        window.c_methods.selectRange(bookRang.start, bookRang.end)
      } else {
        // 公文类
        var arrRember = this.remberTeShuStr.filter((ig) => ig < item.end)
        if (arrRember.length && window.c_methods) {
          // window.alert(arrRember.length)
          window.c_methods.selectRange(
            item.start + arrRember.length + 1,
            item.end + arrRember.length + 1
          )
        } else {
          window.c_methods.selectRange(item.start, item.end)
        }
      }
    },

    // 错误操作
    handleOperateText(item, option) {
      // 将被忽略的词筛选出来
      if (item.opt === '插入' || item.opt === '删除' || item.opt === '替换') {
        this.onProcessClick(item, option)
      }
    },
    // 替换等改变操作
    onProcessClick(item, option) {
      //缺失类不做处理
      if (item.checkType && item.checkType === 'office_deletion') {
        return
      }
      // window.alert(JSON.stringify(item))
      if (!item.bookMarks) {
        this.$message.warning('书签不存在！')
      }
      if (item.opt === '替换') {
        var bookRang = JSON.parse(
          window.c_methods.getBookmark(item.bookMarks)
        ).data
        //设置文字
        window.c_methods.replaceRangeText(
          bookRang.start,
          bookRang.end,
          item.correct
        )
        //更新书签
        window.c_methods.createBookmark(
          item.bookMarks,
          bookRang.start,
          bookRang.start + item.correct.length
        )
        //选中位置
        window.c_methods.selectRange(
          bookRang.start,
          bookRang.start + item.correct.length
        )
        this.DocCheckList[this.docname].map((ig) => {
          if (ig.uid === item.uid && ig.bookMarks === item.bookMarks) {
            ig.status = 2
            ig._end = bookRang.start + item.correct.length
          }
        })
      }

      if (item.opt === '删除') {
        var bookRang = JSON.parse(
          window.c_methods.getBookmark(item.bookMarks)
        ).data
        window.c_methods.replaceRangeText(bookRang.start, bookRang.end, '')
        //更新书签
        window.c_methods.createBookmark(
          item.bookMarks,
          bookRang.start,
          bookRang.start
        )
        this.DocCheckList[this.docname].map((ig) => {
          if (ig.uid === item.uid && ig.bookMarks === item.bookMarks) {
            ig.status = 2
            ig._end = bookRang.start + item.correct.length
          }
        })
      }
      if (item.opt === '插入') {
        let words_new = option || item.words_new
        if (item.pre_insert === 1 || item.pre_insert === '1') {
          words_new = (option || item.words_new) + item.words_wrong //添加词 + 原词
        } else {
          words_new = item.words_wrong + (option || item.words_new) //原词+添加词
        }
        var bookRang = JSON.parse(
          window.c_methods.getBookmark(item.bookMarks)
        ).data
        // 替换
        window.c_methods.replaceRangeText(
          bookRang.start,
          bookRang.end,
          words_new
        )
        //更新书签
        window.c_methods.createBookmark(
          item.bookMarks,
          bookRang.start,
          bookRang.start + words_new.length
        )
        this.DocCheckList[this.docname].map((ig) => {
          if (ig.uid === item.uid && ig.bookMarks === item.bookMarks) {
            ig.status = 2
            ig._end = bookRang.start + item.correct.length
          }
        })
      }
      // 更新列表
      this.setAllList()
    },
    // 撤销替换，撤销删除等操作
    onUnProcessClick(item) {
      if (item.opt === '替换') {
        if (item.bookMarks) {
          var bookRang = JSON.parse(
            window.c_methods.getBookmark(item.bookMarks)
          ).data
          //设置文字
          window.c_methods.replaceRangeText(
            bookRang.start,
            bookRang.end,
            item.words_wrong
          )
          //更新书签
          window.c_methods.createBookmark(
            item.bookMarks,
            bookRang.start,
            bookRang.start + item.words_wrong.length
          )
          //选中位置
          window.c_methods.selectRange(
            bookRang.start,
            bookRang.start + item.words_wrong.length
          )
          // window.alert('66'+JSON.stringify(this.DocCheckList[this.docname]))
          // item.status=1
          this.DocCheckList[this.docname].map((ig) => {
            if (ig.uid === item.uid && ig.bookMarks === item.bookMarks) {
              ig.status = 0
              ig._end = bookRang.start + item.words_wrong.length
            }
          })
        } else {
          this.$message.warning('书签不存在！')
        }
      }
      // 撤销删除
      if (item.opt === '删除') {
        // window.alert(JSON.stringify(item))
        if (
          item.bookMarks &&
          item.bookMarks.indexOf('jiaodui_offline_') !== -1
        ) {
          var bookRang = JSON.parse(
            window.c_methods.getBookmark(item.bookMarks)
          ).data
          // window.alert('删除')
          window.c_methods.replaceRangeText(
            bookRang.start,
            bookRang.end,
            item.words_wrong
          )
          //更新书签
          window.c_methods.createBookmark(
            item.bookMarks,
            bookRang.start,
            bookRang.start + item.words_wrong.length
          )
          this.DocCheckList[this.docname].map((ig) => {
            if (ig.uid === item.uid && ig.bookMarks === item.bookMarks) {
              ig.status = 0
              ig._end = bookRang.start + item.words_wrong.length
            }
          })
        }
      }
      // 更新列表
      this.setAllList()
    },
    // 忽略操作
    handleIgnore(item) {
      this.DocCheckList[this.docname].map((ig) => {
        if (ig.uid === item.uid && ig.bookMarks === item.bookMarks) {
          // window.alert('ig'+JSON.stringify(ig))
          ig.status = 1
        }
      })
      this.setAllList()
    },

    //取消缺失  取消忽略
    onUnIgnore(item) {
      item.status = 0
      // 同时处理已忽略列表中下标相同的
      if (item.checkType !== 'office' || !item.checkType) {
        this.DocCheckList[this.docname].map((ig) => {
          if (ig.uid === item.uid && ig.bookMarks === item.bookMarks) {
            ig.status = 0
          }
        })
      }
      this.setAllList()
    },
    // 清除自定义隐藏Bookmarks
    clearBookmarks(adoc) {
      for (var i = adoc.Bookmarks.Count; i >= 1; i--) {
        if (adoc.Bookmarks.Item(i).Name.includes('Bookmark_')) {
          adoc.Bookmarks.Item(i).Delete() // 删除
        } else if (adoc.Bookmarks.Item(i).Name.includes('Style_')) {
          adoc.Bookmarks.Item(i).Delete() // 删除
        }
      }
    },
  },
}
</script>

<style>
@import './index.css';
</style>
